<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <script src="./static/camera_utils.js" crossorigin="anonymous"></script>
  <script src="./static/control_utils.js" crossorigin="anonymous"></script>
  <script src="./static/control_utils_3d.js" crossorigin="anonymous"></script>
  <script src="./static/drawing_utils.js" crossorigin="anonymous"></script>
  <script src="./static/pose.js" crossorigin="anonymous"></script>
</head>

<body>
  <div class="container">
    <video class="input_video" style="visibility: hidden;"></video>
    <canvas class="output_canvas" width="1280px" height="720px"></canvas>
    <div class="landmark-grid-container"></div>
  </div>


  <script type="module">
    const videoElement = document.getElementsByClassName('input_video')[0];
    const canvasElement = document.getElementsByClassName('output_canvas')[0];
    const canvasCtx = canvasElement.getContext('2d');
    const landmarkContainer = document.getElementsByClassName('landmark-grid-container')[0];
    const grid = new LandmarkGrid(landmarkContainer);

    function onResults (results) {
      if (!results.poseLandmarks) {
        grid.updateLandmarks([]);
        return;
      }

      canvasCtx.save();
      canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
      canvasCtx.drawImage(results.segmentationMask, 0, 0,
        canvasElement.width, canvasElement.height);

      // Only overwrite existing pixels.
      canvasCtx.globalCompositeOperation = 'source-in';
      canvasCtx.fillStyle = 'transparent';
      canvasCtx.fillRect(0, 0, canvasElement.width, canvasElement.height);

      // Only overwrite missing pixels.
      canvasCtx.globalCompositeOperation = 'destination-atop';
      // canvasCtx.drawImage(
      //   results.image, 0, 0, canvasElement.width, canvasElement.height);

      canvasCtx.globalCompositeOperation = 'source-over';
      //
      drawConnectors(canvasCtx, results.poseLandmarks, POSE_CONNECTIONS,
        { color: '#00FF00', lineWidth: 4 });
      drawLandmarks(canvasCtx, results.poseLandmarks,
        { color: '#FF0000', lineWidth: 2 });
      canvasCtx.restore();

      grid.updateLandmarks(results.poseWorldLandmarks);
    }

    const pose = new Pose({
      locateFile: (file) => {
        console.log(file)
        return `./static/${file}`;
      }
    });
    pose.setOptions({
      modelComplexity: 1,
      smoothLandmarks: true,
      enableSegmentation: true,
      smoothSegmentation: true,
      minDetectionConfidence: 0.5,
      minTrackingConfidence: 0.5
    });
    pose.onResults(onResults);

    const camera = new Camera(videoElement, {
      onFrame: async () => {
        await pose.send({ image: videoElement });
      },
      width: 1280,
      height: 720
    });
    camera.start();
  </script>
</body>

</html>